package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.BdmAfterSalesDto;
import com.ruoyi.system.domain.vo.AfterSalesByIdVo;
import com.ruoyi.system.domain.vo.BdmAfterSalesVo;
import com.ruoyi.system.enums.*;
import com.ruoyi.system.mapper.BdmAfterSalesMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 售后记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-02
 */
@Service
public class BdmAfterSalesServiceImpl extends ServiceImpl<BdmAfterSalesMapper, BdmAfterSales> implements IBdmAfterSalesService {
    @Autowired
    private BdmAfterSalesMapper bdmAfterSalesMapper;

    @Autowired
    private IBdmOrderService bdmOrderService;

    @Autowired
    private IBdmOrderItemService bdmOrderItemService;

    @Autowired
    private IBdmGoodService bdmGoodService;

    @Autowired
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private IBdmCloudInventoryService bdmCloudInventoryService;
    @Autowired
    private IBdmCloudInventoryItemService bdmCloudInventoryItemService;

    @Autowired
    private IDistributionService distributionService;

    @Autowired
    private IBdmOrderShipmentsService bdmOrderShipmentsService;

    @Autowired
    private IBdmMemberRuleService bdmMemberRuleService;


    /**
     * 查询售后记录
     *
     * @param id 售后记录主键
     * @return 售后记录
     */
    @Override
    public BdmAfterSales selectBdmAfterSalesById(Long id) {
        return bdmAfterSalesMapper.selectBdmAfterSalesById(id);
    }

    /**
     * 查询售后记录列表
     *
     * @param bdmAfterSales 售后记录
     * @return 售后记录
     */
    @Override
    public List<BdmAfterSales> selectBdmAfterSalesList(BdmAfterSales bdmAfterSales) {
        return bdmAfterSalesMapper.selectBdmAfterSalesList(bdmAfterSales);
    }

    /**
     * 新增售后记录
     *
     * @param bdmAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int insertBdmAfterSales(BdmAfterSales bdmAfterSales) {
        bdmAfterSales.setCreateTime(DateUtils.getNowDate());
        return bdmAfterSalesMapper.insertBdmAfterSales(bdmAfterSales);
    }

    /**
     * 修改售后记录
     *
     * @param bdmAfterSales 售后记录
     * @return 结果
     */
    @Override
    public int updateBdmAfterSales(BdmAfterSales bdmAfterSales) {
        return bdmAfterSalesMapper.updateBdmAfterSales(bdmAfterSales);
    }

    /**
     * 批量删除售后记录
     *
     * @param ids 需要删除的售后记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmAfterSalesByIds(Long[] ids) {
        return bdmAfterSalesMapper.deleteBdmAfterSalesByIds(ids);
    }

    /**
     * 删除售后记录信息
     *
     * @param id 售后记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmAfterSalesById(Long id) {
        return bdmAfterSalesMapper.deleteBdmAfterSalesById(id);
    }

    /**
     * 查询售后记录列表
     */
    @Override
    public List<BdmAfterSalesVo> queryAfterSalesList(BdmAfterSalesDto bdmAfterSalesDto) {
        return bdmAfterSalesMapper.queryAfterSalesList(bdmAfterSalesDto);

    }

    /**
     * 查询售后详情
     */
    @Override
    public AfterSalesByIdVo queryAfterSalesById(Long id) {
        return bdmAfterSalesMapper.queryAfterSalesById(id);

    }

    /**
     * 平台取消退单
     */
    @Override
    public boolean cancelRefund(Long id) {
        BdmAfterSales one = this.lambdaQuery().eq(BdmAfterSales::getId, id).one();
        one.setState(BdmAfterSalesEnum.PLATFORM_CANCELED.getType());
        one.setProcessingTime(DateUtils.getNowDate());
        BdmOrder bdmOrder = bdmOrderService.lambdaQuery().eq(BdmOrder::getId, one.getOrderCode()).one();
        //-------------------新增订单操作日志-------------------
        List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
        //新增订单操作日志
        BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
        bdmOrderShipment.setUserName(bdmOrder.getUserName());
        bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
        bdmOrderShipment.setUserId(bdmOrder.getUserId());
        bdmOrderShipment.setSoId(bdmOrder.getId());
        bdmOrderShipment.setParticulars("商家拒绝退单" + bdmOrder.getId());
        bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.PLATFORM_CANCELS_THE_REFUND.getType());
        bdmOrderShipments.add(bdmOrderShipment);
        //新增订单操作日志
        bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
        //-------------------新增订单操作日志结束-----------------
        //回退订单状态到用户申请退单前
        bdmOrder.setOrderStatus(one.getPreOrderStatus());
        bdmOrderService.updateById(bdmOrder);


        return this.updateById(one);
    }

    /**
     * 平台确认退单
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public int confirmationOfRefund(List<Long> orderIds) {
        for (Long id : orderIds) {
            Date nowDate = DateUtils.getNowDate();
            BdmAfterSales bdmAfterSales = this.lambdaQuery().eq(BdmAfterSales::getId, id).one();
            bdmAfterSales.setState(BdmAfterSalesEnum.COMPLETED.getType());//已完成
            bdmAfterSales.setProcessingTime(nowDate);//处理时间
            bdmAfterSales.setCompletionTime(nowDate);//完成时间
            //修改为已完成
            this.updateById(bdmAfterSales);

            BdmOrder bdmOrder = bdmOrderService.lambdaQuery().eq(BdmOrder::getId, bdmAfterSales.getOrderCode()).one();
            if (bdmOrder.getOrderStatus().equals(BdmOrderEnum.CHARGEBACK.getType())){
                 throw new RuntimeException("订单："+bdmOrder.getId()+"状态无法退款");
            }

            //查看是不是部分退单
//            int i = bdmOrderService.countChargeback(bdmAfterSales.getOrderCode());

//            if (i > 0) {
//                bdmOrder.setOrderStatus(BdmOrderEnum.PARTIAL_REFUND.getType()); //部分退单
//            } else {
//                bdmOrder.setOrderStatus(BdmOrderEnum.CHARGEBACK.getType());//全退
//            }
            bdmOrder.setUpdateTime(DateUtils.getNowDate());
            bdmOrder.setOrderStatus(BdmOrderEnum.CHARGEBACK.getType());

            List<BdmOrderItem> bdmOrderItems = bdmOrderItemService.lambdaQuery()
                    .eq(BdmOrderItem::getOrderId, bdmAfterSales.getOrderCode()).list();

            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                //-------------------新增订单操作日志-------------------
                List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();
                //新增订单操作日志
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(bdmOrder.getUserName());
                bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
                bdmOrderShipment.setUserId(bdmOrder.getUserId());
                bdmOrderShipment.setSoId(bdmOrder.getId());
                bdmOrderShipment.setParticulars("商家同意退单" + bdmOrderItem.getGoodName());
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.REFUND_SUCCESSFUL.getType());
                bdmOrderShipments.add(bdmOrderShipment);
                //新增订单操作日志
                bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
                //-------------------新增订单操作日志结束-----------------
            }


            //商城订单
            if (bdmOrder.getOrderType().equals(BdmGoodEnum.MALL_ORDER.getType())) {
                // 退货
                bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());
            }
            //云库存订单
            if (bdmOrder.getOrderType().equals(BdmGoodEnum.CLOUD_INVENTORY_ORDER.getType())) {
                List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
                for (BdmOrderItem bdmOrderItem : bdmOrderItems) {

                    //商品
                    BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, bdmOrderItem.getSupplierGoodId()).one();
                    //云库存
                    BdmCloudInventory bdmCloudInventory = bdmCloudInventoryService.lambdaQuery()
                            .eq(BdmCloudInventory::getUserId, bdmOrder.getUserId())
                            .eq(BdmCloudInventory::getGoodId, bdmOrderItem.getSupplierGoodId()).one();


                    BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();


                    bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());//云库存id
                    bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
                    bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
                    bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
                    bdmCloudInventoryItem.setNum(Long.parseLong(bdmOrderItem.getGoodCount()));//商品数量
                    bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   减少
                    bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_DELIVERY_REQUEST_RETURN.getDescription());// 提货申请退回
                    bdmCloudInventoryItem.setUserId(bdmOrder.getUserId());//用户id
                    bdmCloudInventoryItem.setCorrelationUserId(bdmOrder.getUserId());//补货上下级  自己
                    bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
                    bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
                    bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
                    bdmCloudInventoryItem.setCreateBy(bdmOrder.getUserId().toString());//创建用户
                    bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
                    bdmCloudInventoryItem.setUpdateBy(bdmOrder.getUserId().toString());//修改用户


                    bdmCloudInventoryItems.add(bdmCloudInventoryItem);
                }
                //回云库存
                bdmCloudInventoryService.addOrRollBackStock(bdmCloudInventoryItems, BdmGoodEnum.ADD.getType());
                //记录云库存明细
                bdmCloudInventoryItemService.saveBatch(bdmCloudInventoryItems);
            }

            //---------------------记录余额积分变动表----------------------

            if (StringUtils.isNotNull(bdmOrder.getPaymentTime()) && bdmOrder.getOrderStatus() != 0) {
                // 已支付 退款(不退运费) TODO 只退了余额
                //退款 记录余额 积分  变更无效佣金  减少累积消费金额
                bdmOrderItemService.refund(bdmOrderItems, bdmOrder.getPayType(), bdmOrder.getUserId());//根据订单项退款

            }
            //---------------------记录余额积分变动表结束----------------------


            //-------------------新增订单操作日志-------------------
            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();

            //新增订单操作日志
            if (!ObjectUtils.isEmpty(bdmOrder)) {
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(bdmOrder.getUserName());
                bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
                bdmOrderShipment.setUserId(bdmOrder.getUserId());
                bdmOrderShipment.setSoId(bdmOrder.getId());
                bdmOrderShipment.setParticulars("订单号为：" + bdmOrder.getId() + " 用户已退单");
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.CUSTOMER_REFUND.getType());
                bdmOrderShipments.add(bdmOrderShipment);
            }
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束------------------

            //---------------------告诉聚水潭退货---------------------
//            List<String> ids = new ArrayList<>();
//            ids.add(bdmOrder.getOId());
//            distributionService.cancelOrder(ids);

            //---------------------告诉聚水潭退货结束------------------

            //---------------------回退用户等级 TODO---------------------
            if (bdmOrder.getOrderType() == 1) {
                BdmMemberRule one = bdmMemberRuleService.lambdaQuery().eq(BdmMemberRule::getSysUserid, bdmOrder.getUserId()).one();
                if (!ObjectUtils.isEmpty(one)) {
                    Long beforMemberLevel = bdmOrder.getBeforMemberLevel();
                    String beforMemberName = bdmOrder.getBeforMemberName();
                    Long beforMemberAgencyLevel = bdmOrder.getBeforMemberAgencyLevel();
                    String beforMemberAgencyLevelName = bdmOrder.getBeforMemberAgencyLevelName();
                    //如果全没有就删除用户会员
                    if (ObjectUtils.isEmpty(beforMemberLevel) && ObjectUtils.isEmpty(beforMemberAgencyLevel)
                            && StringUtils.isEmpty(beforMemberName) && StringUtils.isEmpty(beforMemberAgencyLevelName)) {
                        bdmMemberRuleService.removeById(one.getId());
                    } else {
                        //回退会员等级
                        one.setMemberLevel(beforMemberLevel);
                        one.setMemberName(beforMemberName);
                        one.setMemberAgencyLevel(beforMemberAgencyLevel);
                        one.setMemberAgencyLevelName(beforMemberAgencyLevelName);
                        bdmMemberRuleService.updateById(one);
                    }
                }
            }
            //---------------------回退用户等级结束---------------------
            bdmOrderService.updateBdmOrder(bdmOrder);


        }

        return 1;
    }

    /**
     * 未发货退款
     *
     * @param orderId
     * @return
     */
    @Override
    public AjaxResult refundOrder(String orderId) {
        BdmOrder bdmOrder = bdmOrderService.selectBdmOrderById(orderId);
        if (bdmOrder.getOrderStatus().equals(BdmOrderEnum.SHIPMENTS.getType())) {
            Date nowDate = DateUtils.getNowDate();
            if (bdmOrder.getOrderStatus().equals(BdmOrderEnum.CHARGEBACK.getType())){
                throw new RuntimeException("订单："+bdmOrder.getId()+"状态无法退款");
            }

            //查看是不是部分退单
//            int i = bdmOrderService.countChargeback(bdmAfterSales.getOrderCode());

//            if (i > 0) {
//                bdmOrder.setOrderStatus(BdmOrderEnum.PARTIAL_REFUND.getType()); //部分退单
//            } else {
//                bdmOrder.setOrderStatus(BdmOrderEnum.CHARGEBACK.getType());//全退
//            }
            bdmOrder.setUpdateTime(DateUtils.getNowDate());
            bdmOrder.setOrderStatus(BdmOrderEnum.CHARGEBACK.getType());

            List<BdmOrderShipments> bdmOrderShipments = new ArrayList<>();

            //新增订单操作日志
            if (!ObjectUtils.isEmpty(bdmOrder)) {
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(bdmOrder.getUserName());
                bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
                bdmOrderShipment.setUserId(bdmOrder.getUserId());
                bdmOrderShipment.setSoId(bdmOrder.getId());
                bdmOrderShipment.setParticulars("订单号为：" + bdmOrder.getId() + " 用户已退单");
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.CUSTOMER_REFUND.getType());
                bdmOrderShipments.add(bdmOrderShipment);
            }
            List<BdmOrderItem> bdmOrderItems = bdmOrderItemService.lambdaQuery()
                    .eq(BdmOrderItem::getOrderId, bdmOrder.getId()).list();



            //商城订单
            if (bdmOrder.getOrderType().equals(BdmGoodEnum.MALL_ORDER.getType())) {
                // 退货
                bdmGoodService.addOrRollBackStock(bdmOrderItems, BdmGoodEnum.ADD.getType());
            }
            //云库存订单
            if (bdmOrder.getOrderType().equals(BdmGoodEnum.CLOUD_INVENTORY_ORDER.getType())) {
                List<BdmCloudInventoryItem> bdmCloudInventoryItems = new ArrayList<>();
                for (BdmOrderItem bdmOrderItem : bdmOrderItems) {

                    //商品
                    BdmGood bdmGood = bdmGoodService.lambdaQuery().eq(BdmGood::getId, bdmOrderItem.getSupplierGoodId()).one();
                    //云库存
                    BdmCloudInventory bdmCloudInventory = bdmCloudInventoryService.lambdaQuery()
                            .eq(BdmCloudInventory::getUserId, bdmOrder.getUserId())
                            .eq(BdmCloudInventory::getGoodId, bdmOrderItem.getSupplierGoodId()).one();


                    BdmCloudInventoryItem bdmCloudInventoryItem = new BdmCloudInventoryItem();


                    bdmCloudInventoryItem.setCloudInventoryId(bdmCloudInventory.getId());//云库存id
                    bdmCloudInventoryItem.setGoodId(bdmGood.getId());//商品id
                    bdmCloudInventoryItem.setGoodName(bdmGood.getGoodName());//商品名称
                    bdmCloudInventoryItem.setGoodImg(bdmGood.getGoodImg());//商品图片
                    bdmCloudInventoryItem.setNum(Long.parseLong(bdmOrderItem.getGoodCount()));//商品数量
                    bdmCloudInventoryItem.setNumType(BdmCloudInventoryEnum.NUM_TYPE_ADD.getType());//数量类型   减少
                    bdmCloudInventoryItem.setVariationType(BdmCloudInventoryEnum.TAKE_DELIVERY_REQUEST_RETURN.getDescription());// 提货申请退回
                    bdmCloudInventoryItem.setUserId(bdmOrder.getUserId());//用户id
                    bdmCloudInventoryItem.setCorrelationUserId(bdmOrder.getUserId());//补货上下级  自己
                    bdmCloudInventoryItem.setStockType(BdmCloudInventoryEnum.ACCOMPLISH.getType());//进货状态 已完成
                    bdmCloudInventoryItem.setStockTime(nowDate);//进货时间
                    bdmCloudInventoryItem.setCreateTime(nowDate);//创建时间
                    bdmCloudInventoryItem.setCreateBy(bdmOrder.getUserId().toString());//创建用户
                    bdmCloudInventoryItem.setUpdateTime(nowDate);//修改时间
                    bdmCloudInventoryItem.setUpdateBy(bdmOrder.getUserId().toString());//修改用户


                    bdmCloudInventoryItems.add(bdmCloudInventoryItem);
                }
                //回云库存
                bdmCloudInventoryService.addOrRollBackStock(bdmCloudInventoryItems, BdmGoodEnum.ADD.getType());
                //记录云库存明细
                bdmCloudInventoryItemService.saveBatch(bdmCloudInventoryItems);
            }

            //---------------------记录余额积分变动表----------------------

            if (StringUtils.isNotNull(bdmOrder.getPaymentTime()) && bdmOrder.getOrderStatus() != 0) {
                //退款 记录余额 积分  变更无效佣金  减少累积消费金额

                bdmOrderItemService.refundOrder(bdmOrderItems, bdmOrder.getPayType(), bdmOrder.getUserId());//根据订单项退款

            }
            //---------------------记录余额积分变动表结束----------------------

            for (BdmOrderItem bdmOrderItem : bdmOrderItems) {
                //-------------------新增订单操作日志-------------------
                //新增订单操作日志
                BdmOrderShipments bdmOrderShipment = new BdmOrderShipments();
                bdmOrderShipment.setUserName(bdmOrder.getUserName());
                bdmOrderShipment.setCreateTime(DateUtils.getNowDate());
                bdmOrderShipment.setUserId(bdmOrder.getUserId());
                bdmOrderShipment.setSoId(bdmOrder.getId());
                bdmOrderShipment.setParticulars("商家同意退单" + bdmOrderItem.getGoodName());
                bdmOrderShipment.setOrderStatus(BdmOrderShipmentsEnum.REFUND_SUCCESSFUL.getType());
                bdmOrderShipments.add(bdmOrderShipment);
            }
            //新增订单操作日志
            bdmOrderShipmentsService.saveBdmOrderShipments(bdmOrderShipments);
            //-------------------新增订单操作日志结束------------------

            //---------------------告诉聚水潭退货---------------------
            List<String> ids = new ArrayList<>();
            ids.add(bdmOrder.getOId());
            distributionService.cancelOrder(ids);

            //---------------------告诉聚水潭退货结束------------------

            bdmOrderService.updateBdmOrder(bdmOrder);


        }
        return AjaxResult.success();
    }
}


















